<?php
/**
 * Created by PhpStorm.
 * User: 三星
 * Date: 2018/4/13
 * Time: 22:14
 */

namespace User\Controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Common\Controller\MemberbaseController;
use User\Logic\SmsLogic;

class IntegralController extends MemberbaseController
{

    public function exportall(){
        //需要判断用户身份才可以进行导出数据
        if($this->user['id'] == 207 || $this->user['id'] == 210 ){

        }else{
            $this->error("你没有此权限");
        }

        $begintime = I('begintime');
        $endtime = I('endtime');
        $finalmap = array("status"=>1);
        $filename = '服务卡列表_' . date('YmdHis') . '.csv';
        //由于导出数据增加，改为拼接查询语句
        $seldata = array();
        if($begintime && $endtime){
            $map['createtime'] = array(array('gt', $begintime), array('lt', $endtime));
            $map['lastcosttime'] = array(array('gt', $begintime), array('lt', $endtime));
            $map['_logic'] = 'or';
            //放在外面也会拼接，就会多出来一个and报错了
            $finalmap['_complex'] = $map;
            $seldata['createtime'] = array(array('gt', $begintime), array('lt', $endtime));
        }
        //设置不访问超时
        set_time_limit(0);
        $now = gmdate("D, d M Y H:i:s");

        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment;filename={$filename}");
        header("Content-Transfer-Encoding: binary");
        $lists =D('integral_userinfo')->where($finalmap)->order('createtime desc')->select();

        $datas = array();
        foreach ($lists as $k => $v){
            //遍历的同时查出当月的账目变动
            //扣费金额
            $seldata['type'] = 2;
            $seldata['cardnum'] = $v['cardnum'];
            $kf = M('integral')->where($seldata)->sum('integralchange');
            $seldata['type'] = 1;
            //充值金额
            $cz =  M('integral')->where($seldata)->sum('integralchange');
            $data = [
                $lists[$k]['id'],
                $lists[$k]['cardnum'],
                $lists[$k]['name'],
                $lists[$k]['tel'],
                $lists[$k]['integral']/100,
                $lists[$k]['costcount'],
                $cz/100,
                $kf/100,
                $lists[$k]['remark'],
                $lists[$k]['createtime'],
                $lists[$k]['lastcosttime'],
                $lists[$k]['kaikarenname']
            ];
            $datas[] = $data;
        }
        $head=array('id','服务卡号','姓名','手机','总积分','消费次数','该时间段内充值金额','该时间段内扣费金额','备注','服务卡办理时间','最后消费时间','开卡人');
        ob_start();

        $df = fopen("php://output", 'w');

        if(!$head){
            $head=array_keys(reset($array));
        }

        fputcsv($df,$head);
        foreach ($datas as $row) {
            fputcsv($df, $row);
        }
        fclose($df);

        echo ob_get_clean();
        unset($lists);
        unset($datas);
        die();
    }

    public function index(){
        $cardnum = I('cardnum','','trim');
        $tel = I('tel');
        $name = I('name','','trim');
        $status = I('status',1,'int');

        $data = array();
        $condition = array();
        if($cardnum){
            $data['cardnum'] = $cardnum;
            $condition['cardnum'] = $cardnum;
        }
        if($tel){
            $data['tel'] = array('like','%'.$tel.'%');
            $condition['tel'] = $tel;
        }
        if($status){
            $data['status'] = $status;
            $condition['status'] = $status;
        }
        if($name){
            $data['name'] = array('like','%'.$name.'%');
            $condition['name'] = $name;
        }

        if($this->user['sjquanxian']==1){
            $data['kaikaren'] = $this->user['id'];
        }

        //用户列表，是否需要新建列表D
        $totalsize =D('integral_userinfo')->where($data)->count();
        $page  = $this->page($totalsize, 10);
        $lists = D('integral_userinfo')->where($data)->order('createtime desc')->limit($page->firstRow . ',' . $page->listRows)->select();

        $this->assign('condition',$condition);
        $this->assign('lists',$lists);
        $this->assign('page', $page->show());
        $this->assign('usid',$this->user['id']);
        $this->display();
    }

    public function adduser(){
        if(empty($_POST)){
            $this->display();
        }else{
            $cardnum = I('cardnum','','trim');
            $integral = I('integral');
            $integral *=100;
            $name = I('name');
            $sex = I('sex');
            $tel = I('tel');
            $shenfenzheng = I('shenfenzheng');
            $shengri = I('shengri');
            $remark = I('remark');
            $ui_cardnum = I('ui_cardnum');

            if(M('integral_userinfo')->where(array('cardnum'=>$cardnum))->count()!=0){
                $this->error('该会员卡号已存在！');
            }
            if(!$cardnum){
                $this->error('请正确输入会员卡号！');
            }

            $data = array(
                'cardnum'   => $cardnum,
                'name'      => $name,
                'sex'       => $sex,
                'tel'       => $tel,
                'shenfenzheng' => $shenfenzheng,
                'shengri'   => $shengri,
                'remark'    => $remark,
                'kaikaren'  => $this->user['id'],
                'kaikarenname' => $this->user['user_nicename'],
                'integral'=> $integral,
                'createtime'=>date('Y-m-d H:i:s'),
                'ui_cardnum'=>$ui_cardnum
            );

            if(M('integral_userinfo')->add($data)){
                if($integral){
                    //添加初始化充值内容 只有充值的时候,进行积分的叠加,  积分的消费,在子账号中进行
                    //每次都是新的积分增加
                    M('integral')->add(
                        array(
                            'cardnum'=>$cardnum,
                            'type'=> 1,
                            'name'=>$name,
                            'beforeintegral'=>0,
                            'integralchange'=>$integral,
                            'nowintegral'=>$integral,
                            'createtime'=>date('Y-m-d H:i:s'),
                            'createby'  => $this->user['id'],
                            'createbyuser'=> $this->user['user_nicename'],
                            'temp1'=>1,
                            'remark' => '服务卡开卡初始化.'
                        )
                    );
                }
                if(strlen($tel)==11) {
                    $TemplateParam="{name:'$name',card:'$cardnum',integral:" . $integral/100  . "}";
                    $sms = new SmsLogic();
                    $sms->sendSms($tel,'SMS_211980586',$TemplateParam,1);
                }


                $this->success('添加成功！',UU('Integral/index'));
            }
        }
    }

    public function edituser(){
        if(empty($_POST)){
            $cardnum = I('cardnum');
            $userInfo = D('integral_userinfo')->where(array('cardnum'=>$cardnum))->find();
            if($userInfo){
                $this->assign('userinfo',$userInfo);
                $this->display();
            }else{
                $this->error('卡号错误！');
            }
        }else{
            $cardnum = I('cardnum','','trim');
            $integral = I('integral');
            $name = I('name');
            $sex = I('sex');
            $tel = I('tel');
            $shenfenzheng = I('shenfenzheng');
            $shengri = I('shengri');
            $remark = I('remark');

            $data = array(
                'name'      => $name,
                'sex'       => $sex,
                'tel'       => $tel,
                'shenfenzheng' => $shenfenzheng,
                'shengri'   => $shengri,
                //'integral'  => $integral,
                'remark'    => $remark
            );

            if(M('integral_userinfo')->where(array('cardnum'=>$cardnum))->save($data)!==false){


                $this->success('保存成功！',UU('Integral/index',array('cardnum'=>$cardnum)));
            }else{
                $this->error('保存失败');
            }
        }

    }
    public function changecardnum(){
        if(empty($_POST)){
            $cardnum = I('cardnum','','trim');
            $this->assign('cardnum',$cardnum);
            $this->display();
        }else{
            $cardnum = I('cardnum','','trim');
            $changednum = I('changednum','','trim');
            if($cardnum){
                if($changednum){
                    if(M('integral_userinfo')->where(array('cardnum'=>$changednum))->count()!=0){//存在了不导入
                        $this->error('此卡号已注册，请更换卡号！');
                        return;
                    }
                    M('integral_userinfo')->where(array('cardnum'=>$cardnum))->save(array('cardnum'=>$changednum));
                    M('integral')->where(array('cardnum'=>$cardnum))->save(array('cardnum'=>$changednum));
                    $this->success('修改成功！',UU('Integral/index'));
                }else{
                    $this->error('请输入更改后的卡号');
                }
            }else{
                $this->error('参数错误，无法更改!');
            }
        }
    }

    /*
     * 思考,会员积分功能,需要重新建立新的表结构吗?
     * 这个积分系统就是 给任何人?还是指定任务分发会员卡内容? 如果给任何人,那么就不需要进行记录个人的信息,
     * 如果是分发给指定的人,那么后续还登记使用人的信息吗?
     *
     *
     * 现有内容:
     *      1.需要与原来会员充值的内容区分开来
     *      2.需要多地区同时进行会员积分的充值,
     *
     *
     */
    public function add()
    {
        $cardnum = I('cardnum');
        if ($cardnum) {
            $userinfo = D('integral_userinfo')->where(array('cardnum' => $cardnum))->find();
            if ($userinfo) {
                $this->assign('userinfo', $userinfo);
                $this->assign('cardnum', $cardnum);
                $this->display();
            } else {
                $this->error('请输入正确卡号！');
            }
        } else {
            $this->assign('cardnum', '');
            $this->display();
        }
    }

    public function doadd()
    {
        if ($_POST) {
            $cardnum = I('cardnum');
            $name = I('name','','trim');
            $remark = I('remark');
            //12.21 增加 积分内容 此积分内容为 充值后附送的内容,可以在购买东西时进行扣除
            $integral = I('integral');
            $integral *=100;
            //积分内容需要进行累加,获取上次积分的值,进行叠加
            $oldintegral = I('oldintegral');
            //$oldintegral *=100;
            $tel = I('tel');

            $data = array(
                'cardnum'=>$cardnum,
                'type'=> 1,
                'name'=>$name,
                'beforeintegral'=>$oldintegral,
                'integralchange'=>$integral,
                'nowintegral'=>$integral+$oldintegral,
                'createtime'=>date('Y-m-d H:i:s'),
                'createby'  => $this->user['id'],
                'createbyuser'=> $this->user['user_nicename'],
                'temp1'=>1,
                'remark' => '服务卡充值-->'.$remark
            );
            if(!$integral>0){
                //添加初始化充值内容 只有充值的时候,进行积分的叠加,  积分的消费,在子账号中进行
                //每次都是新的积分增加
                $this->error('请输入正确的充值积分！');
            }
            if( M('integral')->add($data)){
                M('integral_userinfo')->where(array('cardnum'=>$cardnum))
                ->save(
                    array(
                        'lastcosttime'=>date('Y-m-d H:i:s'),
                        'integral'=>$integral+$oldintegral
                    )
                );
                if(strlen($tel)==11) {
                    $TemplateParam = "{name:'$name',card:'$cardnum',change:'充值" . $integral / 100 . "',integral:" . ($integral + $oldintegral) / 100 . "}";
                    $sms = new SmsLogic();
                    $sms->sendSms($tel, 'SMS_211980588', $TemplateParam, 2);
                }
                $this->success('会员充值成功！',UU('User/Integral/index',array('cardnum'=>$cardnum)));
            }
        }else{
            $this->error('请提交正确信息！！');
        }
    }

    public function reduce()
    {
        $cardnum = I('cardnum');
        if ($cardnum) {
            $userinfo = D('integral_userinfo')->where(array('cardnum' => $cardnum))->find();
            if ($userinfo) {
                $this->assign('userinfo', $userinfo);
                $this->assign('cardnum', $cardnum);
                $this->display();
            } else {
                $this->error('请输入正确卡号！');
            }
        } else {
            $this->assign('cardnum', '');
            $this->display();
        }
    }

    public function doreduce(){
        if ($_POST) {
            $cardnum = I('cardnum');
            $name = I('name');
            $remark = I('remark');
            $integral = I('integral');
            $integral *=100;
            $oldintegral = I('oldintegral');
            $tel = I('tel');
            //$oldintegral *=100;
            $costcount = I('costcount',0,'int');
            if($oldintegral-$integral<0){
                $this->error('服务卡余额不足,无发进行此操作！');
            }

            $data = array(
                'cardnum'=>$cardnum,
                'type'=> 2,
                'name'=>$name,
                'beforeintegral'=>$oldintegral,
                'integralchange'=>$integral,
                'nowintegral'=>$oldintegral-$integral,
                'createtime'=>date('Y-m-d H:i:s'),
                'createby'  => $this->user['id'],
                'createbyuser'=> $this->user['user_nicename'],
                'temp1'=>1,
                'remark' => '服务卡消费-->'.$remark
            );

            //添加成功后需要向主表中写入新的数据
            if(M('integral')->add($data)){
                M('integral_userinfo')->where(array('cardnum'=>$cardnum))->save(array('costcount'=>$costcount+1,'integral'=>$oldintegral-$integral));
                if(strlen($tel)==11) {
                    $TemplateParam = "{name:'$name',card:'$cardnum',change:'扣除" . $integral / 100 . "',integral:" . ($oldintegral - $integral) / 100 . "}";
                    $sms = new SmsLogic();
                    $sms->sendSms($tel, 'SMS_211980588', $TemplateParam, 3);
                }
                $this->success('积分扣除成功！',UU('User/integral/reduce'));
            }

        }else{
            $this->error('请提交正确信息！！');
        }
    }

    public function exportintegralhis(){
        //需要判断用户身份才可以进行导出数据
        if($this->user['id'] == 207 || $this->user['id'] == 210 ){

        }else{
            $this->error("你没有此权限");
        }
        $cardnum = I('cardnum_e');
        $name = I('name_e');
        $begintime = I('begintime');
        $endtime = I('endtime');

        $finalmap = array("temp1"=>1);

        $condition = array();
        
        if($begintime && $endtime) {
            $finalmap['createtime'] = array(array('gt', $begintime), array('lt', $endtime));
        }

        if($name){
            $finalmap['name'] = array('like','%'.$name.'%');
            $condition['name'] = $name;
        }

        if($cardnum){
            $finalmap['cardnum'] = $cardnum;
            $condition['cardnum'] = $cardnum;
        }

        $filename = '服务卡历史列表_' . date('YmdHis') . '.csv';
        //设置不访问超时
        set_time_limit(0);
        $now = gmdate("D, d M Y H:i:s");

        header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
        header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
        header("Last-Modified: {$now} GMT");
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Disposition: attachment;filename={$filename}");
        header("Content-Transfer-Encoding: binary");
        $lists =D('integral')->where($finalmap)->select();

        $datas = array();
        foreach ($lists as $k => $v){
            $data = [
                $lists[$k]['cardnum'],
                $lists[$k]['name'],
                $lists[$k]['type']==1?'新增':'消费',
                $lists[$k]['integralchange']/100,
                $lists[$k]['createtime'],
                $lists[$k]['createbyuser'],
                $lists[$k]['remark']
            ];
            $datas[] = $data;
        }
        $head=array('服务卡号','姓名','积分变动类型','积分变动金额','操作时间','开卡人','备注');
        ob_start();

        $df = fopen("php://output", 'w');

        if(!$head){
            $head=array_keys(reset($array));
        }

        fputcsv($df,$head);
        foreach ($datas as $row) {
            fputcsv($df, $row);
        }
        fclose($df);

        echo ob_get_clean();
        unset($lists);
        unset($datas);
        die();
    }

    public function integralhis(){
        $cardnum = I('cardnum');
        $name = I('name');
        $data = array('1'=>'1');
        $condition = array();

        if($name){
            $data['name'] = array('like','%'.$name.'%');
            $condition['name'] = $name;
        }

        if($cardnum){
            $data['cardnum'] = $cardnum;
            $condition['cardnum'] = $cardnum;
        }

        if($this->user['sjquanxian']==1){
            $data['createby'] = $this->user['id'];
        }

        $count = D('integral')->where($data)->count();
        $page = $this->page($count,10);

        $hislist = D('integral')->where($data)->order('createtime desc')->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('url_type',$this->user['url_type']);
        $this->assign('hislist',$hislist);
        $this->assign('condition',$condition);
        $this->assign('page',$page->show());
        $this->assign('usid',$this->user['id']);
        $this->display();
    }

    public function del(){
        $cardnum = I('cardnum');
        if($cardnum){
            M('integral_userinfo')->where(array('cardnum'=>$cardnum))->save(array('status'=>2));
            M('integral')->where(array('cardnum'=>$cardnum))->save(array('temp1'=>'2'));
            $this->success('删除成功！');
        }else{
            $this->error('参数错误，无法删除!');
        }
    }

    public function getUserInfo(){
        $ui_cardnum    = I('ui_cardnum');
        $list   = M('userinfo')->where(array('cardnum'=>$ui_cardnum))->find();
        echo json_encode($list);
    }
}